package com.ptswitch.material.pages.contract;

import java.math.BigDecimal;
import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.util.BigDecimalUtil;
import org.hxzon.util.EMailUtil;
import org.hxzon.util.EMailUtil.EMail;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.ContractService;
import com.ptswitch.material.util.ContractUtil;
import com.ptswitch.material.util.MaterialUtil;
import com.ptswitch.material.util.security.PermissionUtil;

public class ViewContract extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private ContractService contractSer;
    @Property
    private Contract contract;
    private long id;
    //
    @Property
    private String paymentState;
    @Property
    private String undoStr;
    //
    @InjectPage
    private AddItems addContractItem;

    Object withInit(long id) {
        this.id = id;
        return this;
    }

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(long id) {
        withInit(id);
        // init for grid pager
        contract = contractSer.findById(id, ContractService.Init_Items | ContractService.Init_Payments | ContractService.Init_Invoices | ContractService.Init_Uploads);
        checkPermitted(PermissionUtil.ContractView);
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return id;
    }

    @SetupRender
    void display() {
        if (contract == null) {
            return;
        }
        //
        BigDecimal arrears = BigDecimalUtil.subtract(contract.getTotalPrice(), contract.getAccountPaid());
        paymentState = BigDecimalUtil.equals(arrears, BigDecimalUtil.Int0) ? "付款已完成" : ("付款未完成，差额" + arrears);
        undoStr = "";
        if (contract.getNumUnreceiving() > 0) {
            undoStr += "未完成收货，";
        }
        if (contract.getNumUnpassAndUnexamine() > 0) {
            undoStr += "未完成验货，";
        }
        if (BigDecimalUtil.lessThan(contract.getAccountPaid(), contract.getTotalPrice())) {
            undoStr += "未完成付款，";
        }
        if (BigDecimalUtil.lessThan(contract.getInvoicePaid(), contract.getTotalPrice())) {
            undoStr += "未完成发票开具，";
        }
        if (contract.getNumUnreplyPayment() > 0) {
            undoStr += "还有付款申请未处理，";
        }
        if (contract.getNumUnreplyInvoice() > 0) {
            undoStr += "还有发票开具申请未处理";
        }
    }

    @OnEvent(component = "askContractOk")
    Object askContractOk() {
        checkPermitted(PermissionUtil.ContractAskOk);
        contract.setStatus(contract.computeStatusCode());
        contractSer.save(contract);
        //send email
        if (Contract.Status_Ok.equals(contract.getStatus())) {
            EMail email = MaterialUtil.newEMail();
            email.setSubject(contract.getCreater().getRealname() + "标记合同已完成：" + contract.getCode());
            email.addTo(contract.getCreater().getEmail());
            email.addTo(contract.getFinancial().getEmail());
            email.addTo(contract.getProduction().getEmail());
            email.addTo(contract.getAuditor().getEmail());
            email.addHtml(MaterialUtil.linkForViewContract(getWebUrl(), contract));
            EMailUtil.send(email);
        }
        return null;
    }

    @OnEvent(component = "cancelContract")
    Object cancelContract() {
        checkPermitted(PermissionUtil.ContractCancel);
        if (!BigDecimalUtil.equals(contract.getAccountPaid(), BigDecimalUtil.Int0)) {
            setMessage("取消合同失败，请先返回全部付款");
            return null;
        }
        contract.setStatus(Contract.Status_Cancel);
        contractSer.save(contract);
        //send email
        EMail email = MaterialUtil.newEMail();
        email.addTo(contract.getCreater().getEmail());
        email.addTo(contract.getFinancial().getEmail());
        email.addTo(contract.getProduction().getEmail());
        email.addTo(contract.getAuditor().getEmail());
        email.setSubject(contract.getCreater().getRealname() + "取消了合同：" + contract.getCode());
        email.addHtml(MaterialUtil.linkForViewContract(getWebUrl(), contract));
        EMailUtil.send(email);
        return null;
    }

    @OnEvent(component = "askDelete")
    Object askDelete() {
        checkPermitted(PermissionUtil.ContractAskDelete);
        if (!Contract.Status_Cancel.equals(contract.getStatus())) {
            setMessage("申请删除合同失败，请先取消合同");
            return null;
        }
        contract.setAskDelete(true);
        contractSer.save(contract);
        setMessage("已发送删除申请给合同审核人");
        EMail email = MaterialUtil.newEMail();
        email.addTo(contract.getAuditor().getEmail());
        email.setSubject(contract.getCreater().getRealname() + "申请删除合同：" + contract.getCode());
        email.addHtml(MaterialUtil.linkForViewContract(getWebUrl(), contract));
        email.addHtml(MaterialUtil.linkForDeleteContract(getWebUrl(), contract));
        EMailUtil.send(email);
        return null;
    }

    @OnEvent(component = "askReset")
    Object askReset() {
        checkPermitted(PermissionUtil.ContractAskReset);
        if (!Contract.Status_Ok.equals(contract.getStatus())) {
            setMessage("申请激活合同失败，合同必须为已完成");
            return null;
        }
        contract.setAskReset(true);
        contractSer.save(contract);
        setMessage("已发送激活申请给合同审核人");
        EMail email = MaterialUtil.newEMail();
        email.addTo(contract.getAuditor().getEmail());
        email.setSubject(contract.getCreater().getRealname() + "申请激活合同：" + contract.getCode());
        email.addHtml(MaterialUtil.linkForViewContract(getWebUrl(), contract));
        email.addHtml(MaterialUtil.linkForResetContract(getWebUrl(), contract));
        EMailUtil.send(email);
        return null;
    }

    @Override
    protected List<Role> appendRoleToVisitor(Uzer visitor) {
        return ContractUtil.appendThisRole(contract, visitor);
    }
}
